﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BeamRay : MonoBehaviour {
    public Transform endPos;
    public LineRenderer lineRender;
    public Vector3 BeamRayWorldDirection;
    public float MaxDistance;
    public LayerMask layer;

    public GameObject hitObject;

    /// <summary>
    /// 发出的射线是否击中目标
    /// </summary>
    public bool isHit;
    /// <summary>
    /// 是否被要求发出射线
    /// </summary>
    public bool isShoot;



    private void Update()
    {
        if(isShoot)
        {
            RaycastHit hitInfo;
            if (Physics.Raycast(transform.position, BeamRayWorldDirection==Vector3.zero?transform.forward: BeamRayWorldDirection, out hitInfo, MaxDistance, layer.value))
            {
                endPos.position = hitInfo.point;
                if(hitInfo.collider.gameObject!=hitObject)
                {
                    hitObject = hitInfo.collider.gameObject;
                    var beamRayInteractive = hitObject.GetComponent<BeamRayInteractive>();
                    if (beamRayInteractive != null)
                    {
                        beamRayInteractive.AssignBeamRay(this);
                    }
                }
                isHit = true;
            }
            else
            {
                hitObject = null;
                endPos.position = transform.position;
                isHit = false;
            }

            
        }
        else
        {
            isHit = false;
            endPos.position = transform.position;
        }
        lineRender.SetPosition(0, transform.position);
        lineRender.SetPosition(1, endPos.position);


    }
}
